package com.laolei.mongo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Example;
import org.springframework.data.geo.Circle;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.util.MimeTypeUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteResult;
import com.mongodb.DBCollection;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses=UserRepository.class)
public class SpringMongoConfigApplication implements CommandLineRunner{
	@Autowired MongoTemplate mongoTemplate;
	@Autowired GridFsTemplate gridFsTemplate;
	@Autowired UserRepository userRepository;
	ObjectMapper objectMapper=new ObjectMapper();
	public static void main(String[] args) {
		SpringApplication.run(SpringMongoConfigApplication.class, args).close();
	}

	String collectionName="mongo.collection.name.geo.3";
	
	@Override
	public void run(String... args) throws Exception {
//		this.createCollection();
//		this.bulk();
//		this.findUser();
//		this.deleteFile();
//		this.uploadFile(new File("C:/Users/leige/Pictures/壁纸"));
//		this.downloadFile(new File("C:/Users/leige/Downloads"));
	}
	private void createCollection() throws MalformedURLException, IOException{
		DBCollection collection = mongoTemplate.getCollection(collectionName);
		collection.drop();
		mongoTemplate.dropCollection(collectionName);
		collection=mongoTemplate.createCollection(collectionName);
	}
	private void bulk() {
		BulkOperations bulk = mongoTemplate.bulkOps(BulkMode.UNORDERED, collectionName);
		for (int i = 0; i < 10; i++) 
			bulk.insert(new User()); 
		BulkWriteResult rulst = bulk.execute();
		System.err.println(rulst.getInsertedCount());
		List<String> list = mongoTemplate.findAll(String.class, collectionName);
		System.err.println(list );
		userRepository.insert(new User());
		List<User> list1 = mongoTemplate.findAll(User.class,collectionName);
		try {
			System.err.println(objectMapper.writeValueAsString(list1) );
		} catch (JsonProcessingException e) { }
	}
	private void findUser() {
		long count=userRepository.count();
		System.err.println("count="+count);
//		mongoTemplate.dropCollection(User.class);
//		mongoTemplate.createCollection(User.class);
//		userRepository.deleteAll();
		for (int i = 0; i < 1000000; i++) 
			userRepository.insert(new User());
		User users = userRepository.insert(new User());
		System.err.println(users);
		count=userRepository.count();
		System.err.println("count: "+count);
		System.err.println("exists: "+ userRepository.exists(users.getUserid()));
		User u = userRepository.findOne(Example.of(users));
		System.err.println(u);
	}
	
	private void downloadFile(File tagdir) {
		List<GridFSDBFile> gridFss = gridFsTemplate.find(Query.query(GridFsCriteria.whereFilename().exists(true)));
		gridFss.forEach(gridFS->{
			System.err.println(gridFS);
			try {
				gridFS.writeTo(new File(tagdir,gridFS.getFilename()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}
	
	private void deleteFile() {
		gridFsTemplate.delete(Query.query(GridFsCriteria.whereFilename().exists(true)));
	}
	
	private void uploadFile(File dir) throws MalformedURLException, IOException {
		File[] fs = dir.listFiles(t->t.exists()&&t.isFile()&&t.getName().endsWith(".jpg"));
		for (File file : fs) {
			InputStream content= file.toURI().toURL().openStream();
			String filename=file.getName();
			GridFSFile gf = gridFsTemplate.store(content, filename,MimeTypeUtils.IMAGE_JPEG_VALUE,new BasicDBObject(DigestUtil.SHA1, DigestUtil.getFileMD5(file, DigestUtil.SHA1)));
			System.err.println(gf);
		}
	}
	
}
